package com.rbmh.network.controller;

import com.rbmh.network.bean.R;
import com.rbmh.network.bean.entity.DbInfo;
import com.rbmh.network.bean.entity.DbInfoDto;
import com.rbmh.network.bean.entity.DbInfoVo;
import com.rbmh.network.service.DbConnectService;
import com.rbmh.network.utils.NetworkUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/network")
public class NetworkTestController {

    @Autowired
    private DbConnectService dbConnectService;

    @PostMapping("/ping")
    public R testPing(
            @RequestBody DbInfo dbInfo) {

        boolean success = NetworkUtils.ping(dbInfo, 1000);
        log.info("Ping测试结果 - 地址: {}, IP: {}, 结果: {}",dbInfo.getProvince()+ dbInfo.getCity()+dbInfo.getDistrict()+dbInfo.getDetailAddress(), dbInfo.getIpAddress(), success);

        if (success){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    // 新增的数据库连接测试方法
    @PostMapping("/dbconnect")
    public R<Map<String, Object>> testDatabaseConnection(@RequestBody DbInfo dbInfo) {

        log.info("数据库连接测试入参 - 地址: 省{},市{},区县{},详细地址{}, IP: {}, 端口: {}, 数据库: {}, 用户名: {}, 密码: {}}",dbInfo.getProvince(),dbInfo.getCity(),dbInfo.getDistrict(),dbInfo.getDetailAddress(), dbInfo.getIpAddress(), dbInfo.getPort(), dbInfo.getDbName(), dbInfo.getUsername(), dbInfo.getPassword());

        boolean isConnected = dbConnectService.dbConnect(dbInfo);




        if (isConnected){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @PostMapping("/selectByPage")
    public R<DbInfoVo> selectByPage(
            @RequestBody(required = false) DbInfoDto dbInfoDto) {

        Map<String, Object> response = new HashMap<>();

        try {
            DbInfo dbInfo = new DbInfo();

            dbInfo.setProvince(dbInfoDto.getProvince());
            dbInfo.setCity(dbInfoDto.getCity());
            dbInfo.setDistrict(dbInfoDto.getDistrict());
            dbInfo.setDetailAddress(dbInfoDto.getDetailAddress());
            dbInfo.setIpAddress(dbInfoDto.getIpAddress());
            dbInfo.setPort(dbInfoDto.getPort() > 0?dbInfoDto.getPort():0);
            dbInfo.setDbName(dbInfoDto.getDbName());
            dbInfo.setUsername(dbInfoDto.getUsername());
            dbInfo.setPassword(dbInfoDto.getPassword());

            int pageNum = dbInfoDto.getPageNum() > 0?dbInfoDto.getPageNum():1;
            int pageSize = dbInfoDto.getPageSize() > 0?dbInfoDto.getPageSize():10;
            String orderBy = dbInfoDto.getOrderBy();
            String orderDir = dbInfoDto.getOrderDir();



            // 处理分页参数
            int offset = (pageNum - 1) * pageSize;

            // 设置默认排序字段，防止SQL注入
            if (!"id".equals(orderBy) && !"create_time".equals(orderBy) && !"update_time".equals(orderBy)) {
                orderBy = "id";
            }

            // 设置排序方向，防止SQL注入
            if (!"ASC".equalsIgnoreCase(orderDir) && !"DESC".equalsIgnoreCase(orderDir)) {
                orderDir = "DESC";
            }

            // 根据传入的参数决定查询条件
            String province = (dbInfo != null && dbInfo.getProvince() != null && !dbInfo.getProvince().trim().isEmpty())
                    ? dbInfo.getProvince().trim() : null;
            String city = (dbInfo != null && dbInfo.getCity() != null && !dbInfo.getCity().trim().isEmpty())
                    ? dbInfo.getCity().trim() : null;
            String district = (dbInfo != null && dbInfo.getDistrict() != null && !dbInfo.getDistrict().trim().isEmpty())
                    ? dbInfo.getDistrict().trim() : null;
            String detailAddress = (dbInfo != null && dbInfo.getDetailAddress() != null && !dbInfo.getDetailAddress().trim().isEmpty())
                    ? dbInfo.getDetailAddress().trim() : null;
            String ipAddress = (dbInfo != null && dbInfo.getIpAddress() != null && !dbInfo.getIpAddress().trim().isEmpty())
                    ? dbInfo.getIpAddress().trim() : null;

            // 调用service进行分页查询
            List<DbInfo> data = dbConnectService.selectByPage(
                    province,
                    city,
                    district,
                    detailAddress,
                    ipAddress,
                    orderBy,
                    orderDir,
                    offset,
                    pageSize
            );

            // 获取总记录数
            int total = dbConnectService.countByConditions(
                    province,
                    city,
                    district,
                    detailAddress,
                    ipAddress
            );

            DbInfoVo dbInfoVo = new DbInfoVo(data, pageNum, pageSize, total > 0 ? (total + pageSize - 1) / pageSize : 0,total, orderBy, orderDir);

            return R.ok(dbInfoVo);
        } catch (Exception e) {
            log.error("分页查询失败", e);
            return R.fail(e.getMessage());
        }
    }

    @PostMapping("/deleteById")
    public R<Map<String, Object>> deleteById(@RequestBody DbInfo dbInfo) {

        int i = dbConnectService.deleteById(dbInfo.getId());

        if (i >= 1){
            return R.ok("删除成功");
        }else {
            return R.fail("删除失败");
        }
    }
}

